from flask import render_template, current_app, request, jsonify, g

from info import constants
from info.models import News, Category
from info.response_code import RET
from info.utils.common import user_login_data
from . import index_blu


@index_blu.route("/")
@user_login_data
def index():

    # 获取点击排行数据
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_click_list = []

    for news in news_list if news_list else []:
        news_click_list.append(news.to_basic_dict())

    # 获取新闻分类数据
    categories = None
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_list = []
    for cat in categories if categories else []:
        category_list.append(cat.to_dict())

    # 将用户信息返回前端
    data = {"user_info": g.user.to_dict() if g.user else None,
            'news_click_list': news_click_list,
            'category_list':category_list
            }
    return render_template('news/index.html',data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route('/news_list')
def news_list():
    """获取指定分类新闻列表"""

    # 获取参数
    # 新闻分类id
    cid = request.args.get('cid','1')
    # 页数，不传即获取第1页
    page = request.args.get('page','1')
    # 	每页多少条数据，如果不传，默认10条
    per_page = request.args.get('per_page','10')

    # 校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    filters = []
    # 如果不是最新的数据
    if cid != 1:
        # 需要添加的条件
        filters.append(News.category_id == cid)

    # 添加审核通过条件
    filters.append(News.status == 0)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,error_out=False)
        news_li = paginate.items
        total_pages = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return  jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

    news_dict_list = []
    for news in news_li:
        news_dict_list.append(news.to_basic_dict())
    # 返回数据
    data={
        'news_dict_list': news_dict_list,
        'total_pages': total_pages,
        'current_page': current_page
    }

    return jsonify(errno=RET.OK, errmsg='OK', data=data)